package org.xtext.runtime.plan;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.xtext.runtime.formula.IFormula;
import org.xtext.runtime.interpreter.Agent;
import org.xtext.runtime.term.Variable;
import org.xtext.runtime.util.Bindings;

public class QueryStep implements IPlanStep {
	private IFormula guard;
	
	public QueryStep(IFormula guard) {
		this.guard = guard;
	}
	
	@Override
	public QueryStep apply(Bindings set) {
		guard.apply(set);
		return this;
	}

	public String toString() {
		return toString("");
	}

	public String toString(String tabs) {
		return tabs + "query (" + guard + ")";
	}

	public String toFullString(String tabs) {
		return tabs + "query (" + guard + ")";
	}

	public IFormula guard() {
		return guard;
	}
	
	@Override
	public void handle(Agent agent, PlanStack planStack) {
		List<Bindings> result = agent.query(guard);
		if (result == null) {
			agent.logAction(toString() + " [FAILED: NOT MATCHING BELIEFS]");
			planStack.fail();
		} else {
			guard.apply(result.get(0));
			agent.logAction(toString() + " [SUCCESS]");
		}
	}

	@Override
	public Set<Variable> variables() {
		Set<Variable> variables = new HashSet<Variable>();
		variables.addAll(guard.variables());
		return variables;
	}

	@Override
	public IPlanStep copy(Map<String, Variable> vars) {
		return new QueryStep(guard.copy(vars));
	}

	@Override
	public void reset() {
	}
}
